package com.manage.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * @author Fitch
 */
public class ImageComposeUtil {

    /**
     *合成图片 写到指定路径
     * @param mainImageSrc 主图路径（背景图）
     * @param lessImageSrc 小图路径数组（要合成的小图）
     * @param coordinates 对应小图的坐标位置
     * @param objSrc 保存合成图片路径
     */
    public static void composeImage(String mainImageSrc, String[] lessImageSrc, List<String> coordinates,String objSrc,String imgFormat){

        if(lessImageSrc.length != coordinates.size()){
            System.out.println("小图个数与坐标不匹配！");
            return;
        }
        Long t1 = Calendar.getInstance().getTimeInMillis();
        try {
            //主图
            BufferedImage mainImg = ImageIO.read(new File(mainImageSrc));
            //小图
            int i=1;
            List<BufferedImage> bufferedImages = new ArrayList<>();
            for(String s:lessImageSrc){
                BufferedImage bufferedImage= ImageIO.read(new File(s));
                bufferedImages.add(bufferedImage);
            }
            Image image=mainImg.getScaledInstance(mainImg.getWidth(), mainImg.getHeight(), Image.SCALE_SMOOTH);
            BufferedImage bufferedImage2=new BufferedImage(mainImg.getWidth(),  mainImg.getHeight(), BufferedImage.TYPE_INT_BGR);
            Graphics2D g = bufferedImage2.createGraphics();
            g.drawImage(image, 0, 0,null);
            int k=0;
            for(BufferedImage b:bufferedImages){
                String coordinate= coordinates.get(k);
                String[] temp = coordinate.split(",");
                double x=Double.parseDouble(temp[0])*bufferedImage2.getWidth();
                double y =(1-Double.parseDouble(temp[1]))*bufferedImage2.getHeight();
                g.drawImage(b, StrUtil.getInt(x), StrUtil.getInt(y), b.getWidth(), b.getHeight(), null);
                k++;
            }
            g.dispose();
            Long t2 = Calendar.getInstance().getTimeInMillis();
            System.out.println(t2-t1);
            File file = new File(objSrc);
            if(!file.exists()){
                file.mkdirs();
            }
            ImageIO.write(bufferedImage2, "jpg", new File(objSrc+"\\"+(t2-t1)+"."+(StrUtil.isEmpty(imgFormat)?"jpg":imgFormat)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     *合成图片 返回base64
     * @param mainImageSrc 主图路径（背景图）
     * @param lessImageSrc 小图路径数组（要合成的小图）
     * @param coordinates 对应小图的坐标位置
     * @param imgFormat 生成图片格式
     */
    public static String composeImageReturnBase64(String mainImageSrc, String[] lessImageSrc, List<String> coordinates,String imgFormat){
        if(lessImageSrc.length != coordinates.size()){
            System.out.println("小图个数与坐标不匹配！");
            return "";
        }
        Long t1 = Calendar.getInstance().getTimeInMillis();
        try {
            //主图
            BufferedImage mainImg = ImageIO.read(new File(mainImageSrc));
            //小图
            int i=1;
            List<BufferedImage> bufferedImages = new ArrayList<>();
            for(String s:lessImageSrc){
                BufferedImage bufferedImage= ImageIO.read(new File(s));
                bufferedImages.add(bufferedImage);
            }
            Image image=mainImg.getScaledInstance(mainImg.getWidth(), mainImg.getHeight(), Image.SCALE_SMOOTH);
            BufferedImage bufferedImage2=new BufferedImage(mainImg.getWidth(),  mainImg.getHeight(), BufferedImage.TYPE_INT_BGR);
            Graphics2D g = bufferedImage2.createGraphics();
            g.drawImage(image, 0, 0,null);
            int k=0;
            for(BufferedImage b:bufferedImages){
                String coordinate= coordinates.get(k);
                String[] temp = coordinate.split(",");
                double x=Double.parseDouble(temp[0])*bufferedImage2.getWidth();
                double y =(1-Double.parseDouble(temp[1]))*bufferedImage2.getHeight();
                g.drawImage(b, StrUtil.getInt(x), StrUtil.getInt(y), b.getWidth(), b.getHeight(), null);
                k++;
            }
            g.dispose();
            Long t2 = Calendar.getInstance().getTimeInMillis();
            //耗时
            System.out.println("耗时："+(t2-t1)+"ms");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage2,(StrUtil.isEmpty(imgFormat)?"jpg":imgFormat), bos);
            byte[] imageBytes = bos.toByteArray();
            return  "data:image/" + (StrUtil.isEmpty(imgFormat)?"jpg":imgFormat) + ";base64," +EncodesUtil.encodeBase64(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public static final void main(String[] args) {
        String mainSrc ="C:\\KDR\\bg\\bg.jpg";
        String lessSrc = "C:\\KDR\\less";
        String objSrc = "C:\\KDR";
        File file = new File(lessSrc);
        File[] files = file.listFiles();
        String[] images = new String[files.length];
        int i=0;
        for(File f:files){
            images[i] = f.toString();
            i++;
        }
        List<String> coordinates = new ArrayList<>();
        coordinates.add("0.38,0.5");
        coordinates.add("0.58,0.5");
        coordinates.add("0.38,0.3");
        coordinates.add("0.58,0.3");
        composeImage(mainSrc,images,coordinates,objSrc,null);
        System.out.println(composeImageReturnBase64(mainSrc,images,coordinates,"jpg"));
        //overlapImage("C:\\KDR\\bg.jpg", "C:\\KDR\\sm1.png","C:\\KDR\\sm2.png");
    }
}
